package bank.datasource;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.commons.dbcp2.BasicDataSource;

/*
 * BasicDataSource를 관리
 * - BasicDataSource를 instance 변수로 가지고 있으면서 Connection을 제공.
 * - Connection, Statement, ResultSet을 close 메소드 제공.
 * - 싱글톤 패턴으로 구현
 */
public class DatabaseUtil {
	private static BasicDataSource dataSource;
	private static DatabaseUtil instnace = new DatabaseUtil();
	
	private DatabaseUtil() {
		//dataSource 객체 생성 후 설정.
		dataSource = new BasicDataSource();
		dataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver");
		dataSource.setUrl("jdbc:oracle:thin:@127.0.0.1:1521:XE");
		dataSource.setUsername("scott");
		dataSource.setPassword("tiger");
		
		//connection Pool 관련설정
		dataSource.setInitialSize(10);
		dataSource.setMaxTotal(20);
	}
	public static DatabaseUtil getInstance() {
		return instnace;
	}
	
	public Connection getConnection() throws SQLException {
		return dataSource.getConnection();
	}
	//close
	public void close(Connection conn, Statement stmt) throws SQLException{
		if(stmt != null) conn.close();
		if(conn != null) conn.close();
	}
	
	public void close(Connection conn, Statement stmt, ResultSet rs) throws SQLException{
		if(rs != null) rs.close();
		close(conn, stmt);
	}
}
